package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.viewbinding.ViewBinding;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentV2;
import com.zahb.qadx.databinding.FragmentCurriculumDetailsBinding;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.TeacherModel;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.AttentionDetailActivity;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Zdw on 2020/10/26 16:44
 * 课程详情Tab
 */
public class CurriculumDetailsFragment extends BaseFragmentV2 {

    AppCompatImageView mIvTeacherIcon;
    AppCompatTextView mTvTeacherProfiles;
    AppCompatTextView mTvCurriculumProfiles;
    AppCompatTextView mTvCurriculumCharacteristic;

    private static final String sDefaultStr = "暂无内容，请等待后续更新";
    private final Gson mGson = new Gson();
    private TeacherModel.TeacherData mTeacherData;

    public static CurriculumDetailsFragment newInstance(Curriculum curriculum, int from) {
        Bundle args = new Bundle();
        args.putSerializable("curriculum", curriculum);
        args.putInt("from", from);
        CurriculumDetailsFragment fragment = new CurriculumDetailsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @org.jetbrains.annotations.Nullable
    @Override
    public ViewBinding initViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container) {
        FragmentCurriculumDetailsBinding binding = FragmentCurriculumDetailsBinding
                .inflate(inflater, container, false);
        mIvTeacherIcon = binding.ivTeacherIcon;
        mIvTeacherIcon.setOnClickListener(v -> onViewClicked());
        mTvTeacherProfiles = binding.tvTeacherProfiles;
        mTvCurriculumProfiles = binding.tvCurriculumProfiles;
        mTvCurriculumCharacteristic = binding.tvCurriculumCharacteristic;
        return binding;
    }

    @Override
    protected void initViews(View rootView) {
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTvTeacherProfiles.setText(sDefaultStr);
        mTvCurriculumProfiles.setText(sDefaultStr);
        mTvCurriculumCharacteristic.setText(sDefaultStr);
        Curriculum curriculum = (Curriculum) mArguments.getSerializable("curriculum");
        if (curriculum != null) {
            getTeacherData(curriculum);
            mTvCurriculumProfiles.setText(Html.fromHtml(curriculum.getBriefInstroduce()));
            parseAim(curriculum.getAim());
        }
    }

    private void onViewClicked() {
        if (mTeacherData != null) {
            Intent intent = new Intent(getContext(), AttentionDetailActivity.class);
            intent.putExtra("relationId", mTeacherData.getId() + "");
            intent.putExtra("id", 1);// 类型-讲师
            intent.putExtra("name", mTeacherData.getName());
            intent.putExtra("title", mTeacherData.getTitle());
            intent.putExtra("img", mTeacherData.getHeadPhoto());
            startActivity(intent);
        }
    }

    private void getTeacherData(Curriculum curriculum) {
        Map<String, Object> params = new HashMap<>();
        params.put("courseId", curriculum.getId());
        params.put("requestType", 1);
        params.put("pageSize", -1);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mGson.toJson(params));
        addDisposable(RetrofitService.getNetService().getCurriculumTeacherData(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        if (response.getData() != null) {
                            List<TeacherModel.TeacherData> dataList = response.getData().getList();
                            if (dataList != null && dataList.size() > 0) {
                                mTeacherData = dataList.get(0);
                                ImageLoaderKt.loadImageCircle(mIvTeacherIcon, mTeacherData.getHeadPhoto(), R.drawable.ic_default_portrait);
                                mIvTeacherIcon.setVisibility(View.VISIBLE);
                                mTvTeacherProfiles.setVisibility(View.GONE);
                            }
                        }
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void parseAim(String jsonStr) {
        if (jsonStr != null && jsonStr.startsWith("[") && jsonStr.endsWith("]")) {
            JsonArray array = JsonParser.parseString(jsonStr).getAsJsonArray();
            if (array.size() == 0) {
                mTvCurriculumCharacteristic.setText(sDefaultStr);
                return;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < array.size(); i++) {
                JsonObject object = array.get(i).getAsJsonObject();
                if (object.has("content")) {
                    sb.append(object.get("content").getAsString()).append("\n");
                }
            }
            mTvCurriculumCharacteristic.setText(sb.toString());
        } else {
            mTvCurriculumCharacteristic.setText(sDefaultStr);
        }
    }
}
